package com.gistmap.sideline.service;

import com.gistmap.sideline.entity.Credit;
import com.gistmap.sideline.entity.Task;
import com.gistmap.sideline.entity.User;
import com.gistmap.sideline.entity.Verified;
import com.gistmap.sideline.exception.ResourceNotFoundException;
import com.gistmap.sideline.model.TaskStatus;
import com.gistmap.sideline.model.VerifiedStatus;
import com.gistmap.sideline.payload.CreditRequest;
import com.gistmap.sideline.payload.Result;
import com.gistmap.sideline.payload.VerifiedRequest;
import com.gistmap.sideline.repository.CreditRepository;
import com.gistmap.sideline.repository.UserRepository;
import com.gistmap.sideline.repository.VerifiedRepository;
import com.gistmap.sideline.security.UserPrincipal;
import com.gistmap.sideline.util.HttpUtil;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
@Transactional
public class UserService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CreditRepository creditRepository;
    @Autowired
    private VerifiedRepository verifiedRepository;

    public User get(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
    }

    /**
     * 实名认证
     * @param request
     * @return
     * @throws IOException
     */
    public Result verified(VerifiedRequest request) throws IOException {
        Verified verified = new Verified();
        verified.setCode(request.getCode());
        verified.setName(request.getName());
        Response response = HttpUtil.INSTANCE.vertifiedPost(request);
        if (response.code() == 0) {
            verified.setStatus(VerifiedStatus.SUCCESS);
            verifiedRepository.save(verified);
            return new Result().success("实名认证成功");
        } else {
            verified.setStatus(VerifiedStatus.FAILURE);
            verified.setReason(response.toString());
            verifiedRepository.save(verified);
            return new Result().fail(response.toString());
        }
    }

    public void comment(Long userId, CreditRequest request){
        Task task = taskService.get(request.getTaskId());
        Credit credit = new Credit();
        credit.setCredit(request.isCredit());
        credit.setSatisfaction(request.getSatisfaction());
        credit.setUser(get(userId));
        credit.setTask(task);
        credit.setCreditType(request.getCreditType());
        creditRepository.save(credit);
        // 单方确认
        task.setStatus(TaskStatus.CLOSE);
        taskService.save(task);
    }
}
